const netMessage = {
  "250": "微信临时code失效"
}

var Fly = require("./wx.js") //wx.js为您下载的源码文件
var fly = new Fly; //创建fly实例
var tokenFly = new Fly();
import util from './index.js';
const regeneratorRuntime = util.regeneratorRuntime
import siteInfo from '../siteinfo.js';
const prefix = siteInfo.prefix
const stack = [] //响应失败时缓存请求
let loging = false //响应失败时判断是否正在重新登录中
//添加finally方法
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => {
      throw reason
    })
  );
};

//定义构造请求地址函数
const isWq = false; //是否构造微擎地址
const formatUrl = function (url) {
  if (isWq) {
    let model_name = "longbing_shequpintuan";
    url = `${siteInfo.siteroot}?i=${siteInfo.uniacid}&t=${siteInfo.multiid}&v=${siteInfo.version}&from=wxapp&c=entry&a=wxapp&do=api&m=${model_name}&s=${url}`;
    return url;
  } else {
    url = `${siteInfo.siteroot}${url}`;
    return url
  }
}
//阿里云地址转为本地域名的
const formatImageUrl = function (url) {
  // console.log(url)
  if (url.indexOf(siteInfo.siteroot) > -1) {
    return url
  } else {
    return `${formatUrl("api/Common/getImage")}&path=${url}`
  }
}

//登录
const login = async function () {
  
  let url = "/api/home/user/loginBycode"
  url = formatUrl(url)
  let token;
  try {
    let {
      code
    } = await prefix.pro.login();
    let d = await tokenFly.post(url, {
      code: code
    });
    if (d.data.errNum != 200) {
      throw {
        status: d.data.errNum,
        message: d.data.errMsg
      };
    }
    //登录成功
    let res = d.data.result;
    return res;
  } catch (e) {
    console.log('登录失败报错', e)
    //登录失败报错
    util.hideAll();
    util.networkError(netMessage[e.status] || e.message, e.status);
    return await Promise.reject(e);
  }
}


//设置超时
fly.config.timeout = 20000;


//给所有请求添加自定义header
fly.config.headers = tokenFly.config.headers = {
  "content-type": "application/x-www-form-urlencoded"
}


fly.interceptors.request.use((request) => {

  // let token = prefix.getStorageSync('token');
  let app = getApp()
  let token = app.globalData.token
  if (!token) {
    fly.lock()
    return fly.all([login()])
      .then(fly.spread(function (loginInfo) {
        let {
          token,type
        } = loginInfo;
        request.headers["token"] = token;
        // prefix.setStorageSync("token", token);
        let app = getApp()
        app.globalData.token = token
        app.globalData.isShow = type==1
        return request;
      }))
      .finally(()=>{
        fly.unlock();
      })
      .catch(function (error) {
        console.log(error)
        return
      })
  }
  request.headers["token"] = token;
})

fly.interceptors.response.use(
  function(response){
    if (response.data.errNum == 401 || response.data.errNum == 402 || response.data.errNum == 251) {
      // console.log(response)
      // let app = getApp()
      // let token = prefix.getStorageSync('token');
      // if(response.request.headers.token!=token){ //如果token刷新,直接重新请求
      //   return fly.request(response.request);  
      // }
      // stack.push(response)
      // if(loging) return
      this.lock()
      // if(stack.length==1) {loging = true}
      return login()
        .then((res) => {
          let {
            token,type
          } = res;
          // prefix.setStorageSync("token", token); 
          let app = getApp()
          app.globalData.token = token
          app.globalData.isShow = type==1 //用于判定支付按钮是否显示
        }).finally(() => {
          this.unlock();
        }).then(() => {
          return fly.request(response.request)
          // let arr = []
          // let result = []
          // stack.forEach((el,index)=>{
          //   let item = stack.shift()
          //   arr.push((()=>{
          //     return fly.request(item.request);
          //   })())
          //   let res = ''
          //   result.push(res)
          // })
          // return fly.all(arr).then(fly.spread(function(res1,res2){
          //   if(res1) return res1
          // }))
        })
 
    } else if (response.data.errNum == 203) {
      util.goUrl(`../login/index?openType=${'getPhoneNumber'}`)
    } else {
      return response.data;
    }
  },
  (e) => {
    util.hideAll()
    console.log(e)
    util.networkError(netMessage[e.status] || e.message, e.status);
  }
)

// 定义上传,picture--代表图片 audio--音频 video--视频,默认picture
const uploadFile = async (url, {
  name = "file",
  filePath,
  formData = {
    type: "picture"
  }
} = {}) => {
  url = formatUrl(url)
  try {
    let res = await wx.pro.uploadFile({
      url,
      filePath,
      name,
      formData
    })

    //网络请求错误
    if (res.statusCode != 200) {
      throw {
        message: "上传失败,请检查网络后重试!",
        status: res.statusCode
      };
    }
    //服务器提示错误
    let data = JSON.parse(res.data)

    if (data.errNum != 200) {
      throw {
        message: "上传失败,请检查上传配置后重试!",
        status: res.statusCode
      };
    }
    let _res = data.result
    if (formData.type == 'picture') {
      _res = `${siteInfo.siteroot}${_res.url}`
    }
    return _res
  } catch (e) {
    util.hideAll()
    util.networkError(netMessage[e.status] || e.message);
    return await Promise.reject(e);
  }
}

//统一处理请求
const req = {
  async post(url, param) {
    //构造请求地址
    url = formatUrl(url);
    try {
      let d = await fly.post(url, param)
      console.log(d)
      //报错统一处理
      if (d.errNum != 200) throw d
      
      return d.result

    } catch (d) {
      util.hideAll()

      d.errMsg&& util.showModal(d.errMsg + '')
      return await Promise.reject(d);
    }
  },
  async get(url, param) {
    //构造请求地址
    url = formatUrl(url);
    try {
      let d = await fly.get(url, param)
      console.log(d)
      if (d.errNum != 200) throw d
      return d.result

    } catch (d) {
      util.hideAll()
      if (d.errNum == 400 && d.errMsg == '用户信息不存在！') {
        util.goUrl(`../login/index?openType=${'getUserInfo'}`)
        return
      }

      d.errMsg&&util.showModal(d.errMsg + '')

      return await Promise.reject(d);
    }
  },
  async delete(url, param) {
    //构造请求地址
    url = formatUrl(url);
    try {
      let d = await fly.delete(url, param)
      //服务器提示错误码
      let errorCode = [1];
      //报错统一处理
      if (errorCode.includes(d.code)) throw d
      return d.data

    } catch (d) {
      util.hideAll()
      if (d.code == 1) {
        util.showModal(d.data + '')
      }
      return await Promise.reject(d);
    }
  }
}
export {
  fly,
  req,
  uploadFile,
  formatImageUrl
}